var resErr = require('../lib/util.js').resErr;
var async = require('async');
var DB = require("../lib/db_mysql").DB;

exports.resource_list = function(req,res){
  var parentId = req.param('parentId');
  var db = new DB();
  if(!parentId){
  	return res.json({success:false,msg:'资源父ID不能为空！'});
  }
  var sql_text = "SELECT a.*,(SELECT r.res_name FROM t_sys_resource r WHERE r.res_id=a.parent_res_id) parentname FROM t_sys_resource a WHERE 1=1";
  var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
  var page  = parseInt(req.param("page") || req.param("pageNum") || '1');
  if(parentId) {
  	sql_text += (' and a.parent_res_id='+parentId);
  }
  if(req.param("sort")){
    sql_text += " order by a." + req.param("sort") + " " + req.param("dir");
  }
  db.queryPage(sql_text,null,page,limit,function(err,result){
    if(err) return res.json({success:false,msg:err});
    return res.json(result);
  })
}
//普通树结构
exports.resource_tree = function(req,res){
  var sql_text = "SELECT a.* FROM t_sys_resource a WHERE a.parent_res_id=0 and a.res_enable=0 OR a.res_enable IS NULL ORDER BY a.res_sorder ASC";
  //console.log('resource_tree：'+sql_text);
  var tmp_params = [];
  var db = new DB();
  db.query(sql_text,tmp_params,function(err,datas){
    //console.log(datas);
    if(err) return res.json({success:false,msg:JSON.stringify(err)});
    async.eachSeries(datas,function(item,callback){
      //console.log(item);
      var sql_text2 = "select * from t_sys_resource where parent_res_id = "  + item.res_id + " ORDER BY res_sorder ASC";
      //console.log(sql_text2);
      db.query(sql_text2,[],function(err,sub_datas){
        if(err) return callback(err);
        item.sub_categorys = sub_datas;
        async.eachSeries(sub_datas,function(item3,callback2){
          var sql_text3 = "select * from t_sys_resource where parent_res_id = "  + item3.res_id + " ORDER BY res_sorder ASC";
          db.query(sql_text3,[],function(err,sub_datas_3){
            if(err) return callback2(err);
            item3.sub_categorys = sub_datas_3;
            return callback2(null);
          });
        },function(err){
          if(err) return callback(err);
          return callback(null);
        });
      });
    },function(err){
      if(err) return res.json({success:false,msg:JSON.stringify(err)});
      return res.json(getResourceTree(datas));
    });    
  })
}
//生成树结构数组
function getResourceTree(datas) {
  console.log(datas);
  if(datas) {
    var root_children_list = [];
    for(var i=0;i<datas.length;i++) {
      var childlist = datas[i].sub_categorys;
      var child = {};
      if(childlist) {
        child.id = datas[i].res_id;
        child.text = datas[i].res_name;
        child.leaf = false;
        child.icon = datas[i].icon;
        child.children = getResourceTree(childlist);
        root_children_list.push(child);
      } else {
        child.id = datas[i].res_id;
        child.text = datas[i].res_name;
        child.icon = datas[i].icon;
        child.leaf = true;
        root_children_list.push(child);
      }
    }
    console.log(root_children_list);
    return root_children_list;
  } else {
    return null;
  }
}

exports.getResourceTree = getResourceTree;
//带复选框的树结构，并选中角色已经拥有的资源
exports.resource_checktree = function(req,res){
  var role_id = req.param('role_id');
  var sql_text = "SELECT * FROM t_sys_resource WHERE parent_res_id=0 and res_enable=0 OR res_enable IS NULL ORDER BY res_sorder ASC";
  //console.log('resource_tree：'+sql_text);
  var tmp_params = [];
  var db = new DB();
  db.query(sql_text,tmp_params,function(err,datas){
    //console.log(datas);
    if(err) return resErr(res,err);
    async.eachSeries(datas,function(item,callback){
      //console.log(item);
      var sql_text2 = "select * from t_sys_resource where parent_res_id = "  + item.res_id + " ORDER BY res_sorder ASC";
      //console.log(sql_text2);
      db.query(sql_text2,[],function(err,sub_datas){
        if(err) return callback(err);
        item.sub_categorys = sub_datas;
        async.eachSeries(sub_datas,function(item3,callback2){
          var sql_text3 = "select * from t_sys_resource where parent_res_id = "  + item3.res_id + " ORDER BY res_sorder ASC";
          db.query(sql_text3,[],function(err,sub_datas_3){
            if(err) return callback2(err);
            item3.sub_categorys = sub_datas_3;
            return callback2(null);
          });
        },function(err){
          if(err) return callback(err);
          return callback(null);
        });
      });
    },function(err){
      if(err) res.json({success:false,msg:JSON.stringify(err)});
      if(role_id){
        var sql_text3 = "select res_id from t_sys_resource_role where role_id=?";
        var params = [];
        params.push(role_id);
        db.query(sql_text3,params,function(err,role_res_datas){
          if(err) res.json({success:false,msg:JSON.stringify(err)});
          return res.json(getResourceCheckTree(datas,role_res_datas));
        });
      } else {
        return res.json(getResourceCheckTree(datas,null));
      }
    });    
  });
}
//生成树结构数组
function getResourceCheckTree(datas, role_res_datas) {
  if(datas) {
    var root_children_list = [];
    for(var i=0;i<datas.length;i++) {
      var childlist = datas[i].sub_categorys;
      var child = {};
      if(childlist) {
        child.id = datas[i].res_id;
        child.text = datas[i].res_name;
        child.leaf = false;
        child.checked = ischecked(datas[i].res_id, role_res_datas);
        child.children = getResourceCheckTree(childlist, role_res_datas);
        root_children_list.push(child);
      } else {
        child.id = datas[i].res_id;
        child.text = datas[i].res_name;
        child.leaf = true;
        child.checked = ischecked(datas[i].res_id, role_res_datas);
        root_children_list.push(child);
      }
    }
    return root_children_list;
  } else {
    return null;
  }
}

function ischecked(resource_id, role_res_datas){
  if(role_res_datas && role_res_datas.length > 0){
    var flag = false;
    for(var i=0;i<role_res_datas.length;i++){
      var role_res = role_res_datas[i];
      if(resource_id == role_res.res_id){
        flag = true;
        break;
      }
    }
    return flag;
  } else {
    return false;
  }
}

exports.resource_edit = function(req,res){
  var res_id = req.param('res_id');
  var res_sorder = req.param('res_sorder');
  var parentId = req.param('parentId');
  var res_name = req.param('res_name');
  var res_key = req.param('res_key');
  var res_url = req.param('res_url');
  var res_type = req.param('res_type');
  var res_desc = req.param('res_desc');
  var res_enable = req.param('res_enable');
  var icon = req.param('icon');
  var db = new DB();
  if(!res_id){
  	db.query("update t_sys_resource set res_sorder=res_sorder+1 where parent_res_id="+parentId+" and res_sorder >="+res_sorder,null,function(err,datas){
      if(err) return res.json({success:false,msg:err});
      var params = [];
    	var sql_text = "insert into t_sys_resource(parent_res_id,res_name,res_key,res_url,res_type,res_enable,res_sorder,icon,res_desc) values(?,?,?,?,?,?,?,?,?)"
    	params.push(parentId);
    	params.push(res_name);
    	params.push(res_key);
    	params.push(res_url);
    	params.push(res_type);
    	params.push(res_enable);
    	params.push(res_sorder);
      params.push(icon);
      params.push(res_desc);
    	db.query(sql_text,params,function(err,datas){
	      if(err) return resErr(res, err);
	       return res.json({success:true,msg:'操作成功！'});
	    });
    });
  }else{
  	res_id = parseInt(res_id);
  	parentId = parseInt(parentId);
  	var selSql = "select * from t_sys_resource where res_id = ?";
  	var selParam = [];
  	selParam.push(res_id);
    db.query(selSql,selParam,function(err,datas){
      if(err) return resErr(res, err);
      if(datas.length>0 && datas[0].res_sorder){
      	var updSorderParam = [];
      	var updSorderSql = "update t_sys_resource set res_sorder = res_sorder - 1 where parent_res_id=? and res_sorder > ?";
      	updSorderParam.push(parentId);
      	updSorderParam.push(datas[0].res_sorder);
      	db.query(updSorderSql,updSorderParam,function(err,datas){
	      if(err) return res.json({success:false,msg:err});
	      var updSorderAppendSql = "update t_sys_resource set res_sorder = res_sorder + 1 where parent_res_id=? and res_sorder >=?";
	      var updSorderAppendParams = [];
	      updSorderAppendParams.push(parentId);
	      updSorderAppendParams.push(res_sorder);
	      db.query(updSorderAppendSql,updSorderAppendParams,function(err,datas){
		      if(err) return res.json({success:false,msg:err});
		      var params = [];
		      var sql_text = "update t_sys_resource set res_name=?,res_key=?,res_url=?,res_type=?,res_enable=?,res_sorder=?,res_desc=?,icon=? where res_id=?"
		      params.push(res_name);
		      params.push(res_key);
		      params.push(res_url);
		      params.push(res_type);
		      params.push(res_enable);
		      params.push(res_sorder);
		      params.push(res_desc);
          params.push(icon);
		      params.push(res_id);
		      db.query(sql_text,params,function(err,datas){
			      if(err) return res.json({success:false,msg:err});
			      return res.json({success:true,msg:'修改成功！'});
			  });
		  });
	    });
      } else {
      	return res.json({success:true,msg:'数据不存在或显示顺序未设置正确！'});
      }
    });
  }
}

exports.resource_check = function(req,res){
  var res_key = req.param('res_key');
  if(res_key){
   	var params = [];
	var sql_text = "select count(1) counter from t_sys_resource where res_key=?"
	params.push(res_key);
  var db = new DB();
	db.query(sql_text,params,function(err,datas){
      if(err) return res.json({success:false,msg:err});
      if(datas.length > 0 && datas[0].counter > 0){
        return res.json({success:false,msg:'该资源编码已经被占用！'});
      } else {
      	return res.json({success:true,msg:'该资源编码可用！'});
      }
    });
  } else {
  	return res.json({success:false,msg:'资源编码不能为空！'});
  }
}

exports.resource_del = function(req,res){
  var resource_id = req.param('resource_id');
  console.log('待删除resource_id: '+resource_id);
  if(resource_id === undefined) {
    return res.json({success:false,msg:'资源ID不能为空！'});
  }
  resource_id = parseInt(resource_id);
  var sql_text_1 = "select * from t_sys_resource where parent_res_id = " + resource_id;
  var db = new DB();
  db.query(sql_text_1,[],function(err,datas){
    if(err) return resErr(res,err);
    if(datas && datas.length > 0){
      return res.json({success:false,msg:'当前节点下还有子节点，无法删除！'});
    } else {
      var tmp_params = [];
      var sql_text = "";
      async.waterfall ([
        //资源删除，同时已经授权的资源在权限资源映射表中，也要删除，TODO...
        function(cb){
          sql_text = "delete from t_sys_resource where res_id=?";
          tmp_params = [];
          tmp_params.push(resource_id);
          console.log(sql_text);
          console.log(tmp_params);
          db.query(sql_text,tmp_params,function(err,datas){
            if(err) return res.json({success:false,msg:err});
            return res.json({success:true,msg:'删除成功！'});
          })
        }
      ],function(err){
        if(err) return res.json({success:false,msg:err});
      })
    }
  });
}